/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>
#include "Xern/IResource.hpp"
#include "Xern/FileSystem.hpp"
#include "Xern/DataFilter.hpp"
#include "Xern/Hashes.hpp"
#include "Xern/Log.hpp"
#include "Xern/PluginFactory.hpp"
#include "ResourceCache.hpp"

namespace XernSqliteCache
{
	static PluginFactory<ResourceCache> resourceCacheFactory("ResourceCache", "SqliteCache");

	ResourceCache::ResourceCache()
	{
		cacheFolder = "xern_cache";
		cacheDatabase = NULL;
		findNameStatement = NULL;
		findHashStatement = NULL;
		findPathStatement = NULL;
		findPathByGuidStatement = NULL;
		findGuidStatement = NULL;
		insertNameStatement = NULL;
		updateNameStatement = NULL;
		insertHashStatement = NULL;
		updateNameStatement = NULL;
		renameGuidStatement = NULL;
		insertGuidStatement = NULL;
		updateGuidStatement = NULL;
	}

	ResourceCache::~ResourceCache()
	{
	}

	void ResourceCache::Initialize()
	{
		// Make sure the cache folder exists.
		if(!IsDirectory(cacheFolder))
			MakeDirectory(cacheFolder);

		// Open or create the cache data base.
		int res = sqlite3_open(JoinPath(cacheFolder, "cache.db").c_str(), &cacheDatabase);
		if(res != SQLITE_OK)
		{
			LogConsole->Error("Failed to open/create the cache data base.");
			return;
		}

		// Create the data base tables.
		CreateTables();

		// Create the statements.
		CreateStatements();
	}

	void ResourceCache::Shutdown()
	{
		if(!cacheDatabase)
			return;

		// Close the data base.
		sqlite3_close(cacheDatabase);
		cacheDatabase = NULL;
	}

	void ResourceCache::CreateTables()
	{
		// Data base creation commands.
		const char *commands =
		"BEGIN TRANSACTION;"
		"CREATE TABLE IF NOT EXISTS NameTable"
		"("
			"id INTEGER PRIMARY KEY,"
			"Name TEXT NOT NULL,"
			"GroupName TEXT NOT NULL,"
			"Path TEXT NOT NULL"
		");"
		"CREATE TABLE IF NOT EXISTS GuidTable"
		"("
			"id INTEGER PRIMARY KEY,"
			"Guid TEXT NOT NULL,"
			"Path TEXT NOT NULL"
		");"
		"CREATE TABLE IF NOT EXISTS HashTable"
		"("
			"id INTEGER PRIMARY KEY,"
			"Path TEXT NOT NULL,"
			"Sha256 TEXT NOT NULL"
		");"
		"COMMIT;";

		// Execute the commands.
		char *error = NULL;
		int res = sqlite3_exec(cacheDatabase, commands, NULL, NULL, &error);
		if(res != SQLITE_OK)
		{
			LogConsole->Error("Failed to initialize resource cache database: %s", error);
			sqlite3_free(error);
			return;
		}
	}

	void ResourceCache::CreateStatements()
	{
		// Statements code.
		const char *findNameCode =
					"SELECT Name, GroupName, Path"
					" FROM NameTable"
					" WHERE Name == ?1 AND GroupName == ?2";

		const char *insertNameCode = "INSERT INTO NameTable (Name,GroupName,Path)"
								 " VALUES(?1, ?2, ?3)";
		const char *updateNameCode = "UPDATE NameTable"
						 " SET Name = ?1,"
						 " GroupName = ?2,"
						 " Path = ?3"
						 " WHERE Name == ?1 AND GroupName == ?2";
		const char *insertGuidCode = "INSERT INTO GuidTable (Guid,Path)"
								 " VALUES(?1, ?2)";

		const char *renameGuidCode = "UPDATE GuidTable"
						 " SET Guid = ?2"
						 " WHERE Guid = ?1";
		const char *updateGuidCode = "UPDATE GuidTable"
						 " SET Guid = ?1,"
						 " Path = ?2"
						 " WHERE Guid == ?1";
		const char *findGuidCode =
							"SELECT Path, Guid"
							" FROM GuidTable"
							" WHERE Path == ?1";
		const char *findHashCode =
							"SELECT Path, Sha256"
							" FROM HashTable"
							" WHERE Path == ?1";

		const char *findPathCode =
							"SELECT Sha256, Path"
							" FROM HashTable"
							" WHERE Sha256 == ?1";
		const char *findPathByGuidCode =
							"SELECT Guid, Path"
							" FROM GuidTable"
							" WHERE Guid == ?1";

		const char *insertHashCode = "INSERT INTO HashTable (Path,Sha256)"
								 " VALUES(?1, ?2)";
		const char *updateHashCode = "UPDATE HashTable"
						 " SET Path = ?1,"
						 " Sha256 = ?2"
						 " WHERE Path == ?1";

		// Compile the statements.

		// Find name.
		int res = sqlite3_prepare_v2(cacheDatabase, findNameCode, -1, &findNameStatement, NULL);
		if(res != SQLITE_OK || findNameStatement == NULL)
		{
			LogConsole->Error("Failed to create sqlite statement: %s", sqlite3_errmsg(cacheDatabase));
			return;
		}

		// Insert name.
		res = sqlite3_prepare_v2(cacheDatabase, insertNameCode, -1, &insertNameStatement, NULL);
		if(res != SQLITE_OK || insertNameStatement == NULL)
		{
			LogConsole->Error("Failed to create sqlite statement: %s", sqlite3_errmsg(cacheDatabase));
			return;
		}

		// Update name.
		res = sqlite3_prepare_v2(cacheDatabase, updateNameCode, -1, &updateNameStatement, NULL);
		if(res != SQLITE_OK || updateNameStatement == NULL)
		{
			LogConsole->Error("Failed to create sqlite statement: %s", sqlite3_errmsg(cacheDatabase));
			return;
		}

		// Find hash.
		res = sqlite3_prepare_v2(cacheDatabase, findHashCode, -1, &findHashStatement, NULL);
		if(res != SQLITE_OK || findHashStatement == NULL)
		{
			LogConsole->Error("Failed to create sqlite statement: %s", sqlite3_errmsg(cacheDatabase));
			return;
		}

		// Find path
		res = sqlite3_prepare_v2(cacheDatabase, findPathCode, -1, &findPathStatement, NULL);
		if(res != SQLITE_OK || findPathStatement == NULL)
		{
			LogConsole->Error("Failed to create sqlite statement: %s", sqlite3_errmsg(cacheDatabase));
			return;
		}

		// Find path by guid
		res = sqlite3_prepare_v2(cacheDatabase, findPathByGuidCode, -1, &findPathByGuidStatement, NULL);
		if(res != SQLITE_OK || findPathByGuidStatement == NULL)
		{
			LogConsole->Error("Failed to create sqlite statement: %s", sqlite3_errmsg(cacheDatabase));
			return;
		}

		// Insert hash.
		res = sqlite3_prepare_v2(cacheDatabase, insertHashCode, -1, &insertHashStatement, NULL);
		if(res != SQLITE_OK || insertHashStatement == NULL)
		{
			LogConsole->Error("Failed to create sqlite statement: %s", sqlite3_errmsg(cacheDatabase));
			return;
		}

		// Update hash.
		res = sqlite3_prepare_v2(cacheDatabase, updateHashCode, -1, &updateHashStatement, NULL);
		if(res != SQLITE_OK || updateHashStatement == NULL)
		{
			LogConsole->Error("Failed to create sqlite statement: %s", sqlite3_errmsg(cacheDatabase));
			return;
		}

		// Find Guid
		res = sqlite3_prepare_v2(cacheDatabase, findGuidCode, -1, &findGuidStatement, NULL);
		if(res != SQLITE_OK || findGuidStatement == NULL)
		{
			LogConsole->Error("Failed to create sqlite statement: %s", sqlite3_errmsg(cacheDatabase));
			return;
		}

		// Insert Guid
		res = sqlite3_prepare_v2(cacheDatabase, insertGuidCode, -1, &insertGuidStatement, NULL);
		if(res != SQLITE_OK || insertGuidStatement == NULL)
		{
			LogConsole->Error("Failed to create sqlite statement: %s", sqlite3_errmsg(cacheDatabase));
			return;
		}

		// Update Guid
		res = sqlite3_prepare_v2(cacheDatabase, updateGuidCode, -1, &updateGuidStatement, NULL);
		if(res != SQLITE_OK || updateGuidStatement == NULL)
		{
			LogConsole->Error("Failed to create sqlite statement: %s", sqlite3_errmsg(cacheDatabase));
			return;
		}

		// Rename Guid
		res = sqlite3_prepare_v2(cacheDatabase, renameGuidCode, -1, &renameGuidStatement, NULL);
		if(res != SQLITE_OK || renameGuidStatement == NULL)
		{
			LogConsole->Error("Failed to create sqlite statement: %s", sqlite3_errmsg(cacheDatabase));
			return;
		}
	}

	std::string ResourceCache::CreateFileName()
	{
		assert(NULL);
		return std::string();
	}

	std::string ResourceCache::CreateFileNameById(const uuid &id)
	{
		std::string path = JoinPath(cacheFolder, "uuid-" + boost::lexical_cast<std::string> (id));
		RegisterResourceId(id, path);
		return path;
	}

	std::string ResourceCache::GetResourcePath(boost::shared_ptr<IResource> resource)
	{
		ResourcesPath::const_iterator it = resourcesPath.find(resource);
		if(it != resourcesPath.end())
			return it->second;
		return std::string();
	}

	Sha256 ResourceCache::GetResourceHash(boost::shared_ptr<IResource> resource)
	{
		// First get the resource path.
		std::string path = GetResourcePath(resource);
		if(path.empty())
			return Sha256();

		// Now find the hash.
		sqlite3_bind_text(findHashStatement, 1, path.c_str(), -1, SQLITE_TRANSIENT);

		// Only read the first row.
		std::string hashString;
		int res = sqlite3_step(findHashStatement);
		if(res == SQLITE_ROW)
		{
			// Read the hash.
			hashString = (const char*)sqlite3_column_text(findHashStatement, 1);
		}

		// Reset the statement.
		sqlite3_reset(findHashStatement);

		return Sha256::Parse(hashString);
	}

	uuid ResourceCache::GetResourceId(const std::string &fullpath)
	{
		// Find the guid.
		sqlite3_bind_text(findGuidStatement, 1, fullpath.c_str(), -1, SQLITE_TRANSIENT);

		// Only read the first row.
		uuid id;
		int res = sqlite3_step(findGuidStatement);
		if(res == SQLITE_ROW)
		{
			// Read the guid.
			id = boost::lexical_cast<uuid>((const char*)sqlite3_column_text(findGuidStatement, 1));
		}

		// Reset the statement.
		sqlite3_reset(findGuidStatement);
	}

	boost::shared_ptr<IResource>
	ResourceCache::LoadResource(const std::string &fullpath)
	{
		// Find the loaded resource.
		LoadedResources::iterator it = loadedResources.find(fullpath);
		if(it != loadedResources.end())
		{
			boost::weak_ptr<IResource> weak = it->second;
			boost::shared_ptr<IResource> resource = weak.lock();
			if(resource)
				return resource;

			// Remove expired resources.
			loadedResources.erase(it);
			resourcesPath.erase(weak);
		}

		// Leave this work to the resource manager.
		return boost::shared_ptr<IResource> ();
	}

	std::string ResourceCache::GetCachePath(const Sha256 &hash)
	{
		// Find the path in the data base.
		char hashString[Sha256::StringSize];
		hash.ToString(hashString, Sha256::StringSize);
		sqlite3_bind_text(findPathStatement, 1, hashString, -1, SQLITE_TRANSIENT);

		// Only read the first row.
		std::string path;
		int res = sqlite3_step(findPathStatement);
		if(res == SQLITE_ROW)
		{
			// Read the path.
			path = (const char*)sqlite3_column_text(findPathStatement, 1);
		}

		// Reset the statement.
		sqlite3_reset(findPathStatement);

		// Return the path.
		return path;
	}

	std::string ResourceCache::GetCachePath(const std::string &name, const std::string &group)
	{
		// Do nothing if the name or group is empty.
		if(name.empty() || group.empty())
			return std::string();

		// Find the path in the data base.
		sqlite3_bind_text(findNameStatement, 1, name.c_str(), -1, SQLITE_TRANSIENT);
		sqlite3_bind_text(findNameStatement, 2, group.c_str(), -1, SQLITE_TRANSIENT);

		// Only read the first row.
		std::string path;
		int res = sqlite3_step(findNameStatement);
		if(res == SQLITE_ROW)
		{
			// Read the path.
			path = (const char*)sqlite3_column_text(findNameStatement, 2);
		}

		// Reset the statement.
		sqlite3_reset(findNameStatement);

		// Return the path.
		return path;
	}

	std::string ResourceCache::GetCachePath(const uuid &id)
	{
		if(id.is_nil())
			return std::string();

		// Find the path in the data base.
		sqlite3_bind_text(findPathByGuidStatement, 1, boost::lexical_cast<std::string> (id).c_str(), -1, SQLITE_TRANSIENT);

		// Only read the first row.
		std::string path;
		int res = sqlite3_step(findPathByGuidStatement);
		if(res == SQLITE_ROW)
		{
			// Read the path.
			path = (const char*)sqlite3_column_text(findPathByGuidStatement, 1);
		}

		// Reset the statement.
		sqlite3_reset(findPathByGuidStatement);

		// Return the path.
		return path;
	}

	void ResourceCache::RegisterResourceName(const std::string &name, const std::string &group, const std::string &fullpath)
	{
		// Store an entry into the name table.
		if(!name.empty() && !group.empty() && !fullpath.empty())
		{
			// Try to update first.
			sqlite3_bind_text(updateNameStatement, 1, name.c_str(), -1, SQLITE_TRANSIENT);
			sqlite3_bind_text(updateNameStatement, 2, group.c_str(), -1, SQLITE_TRANSIENT);
			sqlite3_bind_text(updateNameStatement, 3, fullpath.c_str(), -1, SQLITE_TRANSIENT);

			int res = sqlite3_step(updateNameStatement);
			if(res != SQLITE_DONE || sqlite3_changes(cacheDatabase) == 0)
			{
				// Now try to insert.
				sqlite3_bind_text(insertNameStatement, 1, name.c_str(), -1, SQLITE_TRANSIENT);
				sqlite3_bind_text(insertNameStatement, 2, group.c_str(), -1, SQLITE_TRANSIENT);
				sqlite3_bind_text(insertNameStatement, 3, fullpath.c_str(), -1, SQLITE_TRANSIENT);

				// Execute the statement.
				res = sqlite3_step(insertNameStatement);
				if(res != SQLITE_DONE)
				{
					LogConsole->Error("Failed to store resource name in cache: %s", sqlite3_errmsg(cacheDatabase));
				}

				// Reset the statement.
				sqlite3_reset(insertNameStatement);
			}

			// Reset the statement.
			sqlite3_reset(updateNameStatement);
		}
	}

	void ResourceCache::RegisterResourceId(const uuid &id, const std::string &fullpath)
	{
		// Store an entry into the name table.
		if(!id.is_nil() && !fullpath.empty())
		{
			// Try to update first.
			sqlite3_bind_text(updateGuidStatement, 1, boost::lexical_cast<std::string> (id).c_str(), -1, SQLITE_TRANSIENT);
			sqlite3_bind_text(updateGuidStatement, 2, fullpath.c_str(), -1, SQLITE_TRANSIENT);

			int res = sqlite3_step(updateGuidStatement);
			if(res != SQLITE_DONE || sqlite3_changes(cacheDatabase) == 0)
			{
				// Now try to insert.
				sqlite3_bind_text(insertGuidStatement, 1, boost::lexical_cast<std::string> (id).c_str(), -1, SQLITE_TRANSIENT);
				sqlite3_bind_text(insertGuidStatement, 2, fullpath.c_str(), -1, SQLITE_TRANSIENT);

				// Execute the statement.
				res = sqlite3_step(insertGuidStatement);
				if(res != SQLITE_DONE)
				{
					LogConsole->Error("Failed to store resource name in cache: %s", sqlite3_errmsg(cacheDatabase));
				}

				// Reset the statement.
				sqlite3_reset(insertGuidStatement);
			}

			// Reset the statement.
			sqlite3_reset(updateGuidStatement);
		}
	}

	void ResourceCache::RenameResource(const uuid &oldId, const uuid &newId)
	{
		if(oldId.is_nil() || newId.is_nil())
			return;

		// Rename the resource
		sqlite3_bind_text(renameGuidStatement, 1, boost::lexical_cast<std::string> (oldId).c_str(), -1, SQLITE_TRANSIENT);
		sqlite3_bind_text(renameGuidStatement, 2, boost::lexical_cast<std::string> (newId).c_str(), -1, SQLITE_TRANSIENT);
		sqlite3_step(renameGuidStatement);
		sqlite3_reset(renameGuidStatement);
	}

	void ResourceCache::RegisterResourceFile(const std::string &fullpath)
	{
		// Now, update the hash.
		if(!fullpath.empty())
		{
			// Open the file.
			FILE *in = fopen(fullpath.c_str(), "rb");
			if(!in)
				return;

			// Create the data filter.
			boost::shared_ptr<FileFilter> filter(new FileFilter(in, true));

			// Calculate the SHA256 hash.
			Sha256 hash = Sha256::Digest(filter);

			// Create the string representation.
			char hashString[Sha256::StringSize];
			hash.ToString(hashString, Sha256::StringSize);

			// Now, first try to update the hash.
			sqlite3_bind_text(updateHashStatement, 1, fullpath.c_str(), -1, SQLITE_TRANSIENT);
			sqlite3_bind_text(updateHashStatement, 2, hashString, -1, SQLITE_TRANSIENT);

			int res = sqlite3_step(updateHashStatement);
			if(res != SQLITE_DONE || sqlite3_changes(cacheDatabase) == 0)
			{
				// Now, try to insert the hash.
				sqlite3_bind_text(insertHashStatement, 1, fullpath.c_str(), -1, SQLITE_TRANSIENT);
				sqlite3_bind_text(insertHashStatement, 2, hashString, -1, SQLITE_TRANSIENT);

				int res = sqlite3_step(insertHashStatement);
				if(res != SQLITE_DONE)
				{
					LogConsole->Error("Failed to store file hash.");
				}

				// Reset the statement.
				sqlite3_reset(insertHashStatement);
			}

			// Reset the statement.
			sqlite3_reset(updateHashStatement);
		}
	}

	void ResourceCache::ResourceLoaded(boost::shared_ptr<IResource> resource, const std::string &fullpath)
	{
		if(loadedResources.find(fullpath) != loadedResources.end())
			return;

		// Register the loaded resource.
		loadedResources.insert(std::make_pair(fullpath, resource));
		resourcesPath.insert(std::make_pair(resource, fullpath));
	}

}; // namespace XernSqliteCache
